home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_12_06 / allison / hi_lo.c < prev    next >
C/C++ Source or Header  |  1994-04-08  |  2KB  |  85 lines

  1. LISTING 2 - A C program to play HI-LO
  2.  
  3. /* The game of HI-LO - your number in 7 guesses */
  4.  
  5. #include <stdio.h>
  6. #include <ctype.h>
  7.  
  8. main()
  9. {
  10.     int done = 0;       /* Control flag */
  11.  
  12.     puts("Think of a number between 1 and 100.");
  13.     puts("If you don't cheat, I'll figure it out");
  14.     puts("in seven guesses or less!\n");
  15.  
  16.     while (!done)
  17.     {
  18.         int found = 0;  /* Control Flag */
  19.         int lo = 1, hi = 100;
  20.         int guess;
  21.         char response;
  22.  
  23.         /* Play the Game */
  24.         while (!found && lo <= hi)
  25.         {
  26.             /* Get response */
  27.             guess = (lo + hi) / 2;
  28.             printf("Is it %d (L/H/Y): ",guess);
  29.             fflush(stdout);
  30.             scanf("%c%*c",&response);
  31.             response = toupper(response);
  32.  
  33.             /* Narrow the search range */
  34.             if (response == 'L')
  35.                 lo = guess + 1;
  36.             else if (response == 'H')
  37.                 hi = guess - 1;
  38.             else if (response != 'Y')
  39.                 puts("What? Try again...");
  40.             else
  41.                 found = 1;
  42.         }
  43.  
  44.         /* Print results */
  45.         if (lo > hi)
  46.             puts("You cheated!");
  47.         else
  48.         {
  49.             printf("Your number was %d\n",guess);
  50.             puts("What fun!");
  51.         }
  52.  
  53.         printf("Wanna play again? ");
  54.         fflush(stdout);
  55.         scanf("%c%*c",&response);
  56.         if (toupper(response) != 'Y')
  57.             done = 1;
  58.     }
  59.     return 0;
  60. }
  61.  
  62. /* Sample Execution (numbers are 37 and 99)
  63. c:>hi-lo
  64. Think of a number bewteen 1 and 100.
  65. If you don't cheat, I'll figure it out
  66. in seven guesses or less!
  67.  
  68. Is it 50 (L/H/Y): h
  69. Is it 25 (L/H/Y): l
  70. Is it 37 (L/H/Y): y
  71. Your number was 37
  72. What fun!
  73. Wanna play again? y
  74. Is it 50 (L/H/Y): l
  75. Is it 75 (L/H/Y): l
  76. Is it 88 (L/H/Y): l
  77. Is it 94 (L/H/Y): l
  78. Is it 97 (L/H/Y): l
  79. Is it 99 (L/H/Y): l
  80. Is it 100 (L/H/Y): h
  81. You cheated!
  82. Wanna play again? n
  83. */
  84.  
  85.